package file_kit

import (
	"bufio"
	"bytes"
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"github.com/pkg/errors"
	"io"
	"io/ioutil"
	"mime/multipart"
	"os"
	"path"
	"regexp"
)

const ERR_DirNoExist = "dirPath is not exist"

func IsFileExist(filePath string) bool {
	_, err := os.Stat(filePath)
	if err == nil {
		return true
	}
	return false
}

func IsPermitted(filePath string) bool {
	_, err := os.Stat(filePath)
	return os.IsPermission(err)
}

func MakeFullDireCtory(path string, mode os.FileMode) error {
	return os.MkdirAll(path, mode)
}

func RemoveFileOrDir(path string) error {
	return os.Remove(path)
}

func CreatFile(fileName string, isTruncate bool) (*os.File, error) {
	if IsFileExist(fileName) {
		if isTruncate {
			return os.Create(fileName)
		}
		return os.OpenFile(fileName, os.O_RDWR, 0666)
	}
	return os.Create(fileName)
}

func ReadEntireFile(filePath string) ([]byte, error) {
	if IsFileExist(filePath) {
		return ioutil.ReadFile(filePath)
	}
	return nil, errors.New("File no found")
}

func ReadDiretoryInfo(dirPath string) ([]os.FileInfo, error) {
	dirInfo, _ := os.Stat(dirPath)
	if dirInfo == nil {
		return nil, fmt.Errorf(ERR_DirNoExist)
	}
	if !dirInfo.IsDir() {
		return nil, fmt.Errorf("dirPath is not a directory")
	}
	fileInfo, err2 := ioutil.ReadDir(dirPath)
	if err2 == nil {
		return fileInfo, nil
	}
	return nil, err2
}

func FilterFile(files []os.FileInfo, fileNamePattern string) (result []os.FileInfo) {
	result = []os.FileInfo{}
	if files == nil {
		return
	}
	patternCheck := regexp.MustCompile(fileNamePattern)
	for _, oneFile := range files {
		if !oneFile.IsDir() && patternCheck.MatchString(oneFile.Name()) {
			result = append(result, oneFile)
		}
	}
	return
}

func WriteFile(filePath string, data []byte, isAppend bool) error {
	if IsFileExist(filePath) {
		if isAppend {
			file, err := OpenFile(filePath, os.O_RDWR|os.O_APPEND, 0666)
			if err == nil {
				defer func() {
					file.Sync()
					file.Close()
				}()
				n, err2 := bufio.NewWriter(file).Write(data)
				if err2 == nil && n < len(data) {
					return io.ErrShortWrite
				}
				return err2
			}
			return err
		}
		return ioutil.WriteFile(filePath, data, 0666)
	}
	return fmt.Errorf("file no exist")
}

func ReadFilePartly(filePath string) ([]byte, error) {
	if IsFileExist(filePath) {
		file, err := os.OpenFile(filePath, os.O_RDONLY, os.ModePerm)
		defer file.Close()
		if err == nil {
			fileInfo, _ := file.Stat()
			result := make([]byte, 0, fileInfo.Size())
			for {
				partsBytes := make([]byte, 64)
				bytesNum, err2 := file.Read(partsBytes)
				if bytesNum == 0 && err2 == io.EOF {
					break
				}
				result = append(result, partsBytes[:bytesNum]...)
			}
			return result, nil
		}
		return nil, fmt.Errorf("opening file exception:" + err.Error())
	}
	return nil, fmt.Errorf("fild no found")
}

func OpenFile(filePath string, flag int, fileMode os.FileMode) (*os.File, error) {
	if !IsFileExist(filePath) {
		err := MakeFullDireCtory(path.Dir(filePath), fileMode)
		if err == nil {
			return CreatFile(filePath, false)
		}
	} else {
		return os.OpenFile(filePath, flag, fileMode)
	}
	return nil, errors.New("Open file exception")
}

func OpenFileWithBuffer(filePath string, flag int, fileMode os.FileMode) (*bytes.Buffer, error) {
	if IsFileExist(filePath) {
		file, err := OpenFile(filePath, flag, fileMode)
		if err != nil {
			return nil, err
		}
		fileBytes, err2 := ioutil.ReadAll(file)
		if err2 == nil {
			return bytes.NewBuffer(fileBytes), nil
		}
		return nil, err2
	}
	return nil, errors.New("File no found")
}

func SaveNewFileToDirectory(dirName, fileName string, content []byte) error {
	if !IsFileExist(dirName) {
		MakeFullDireCtory(dirName, os.ModePerm)
	}
	_, err := CreatFile(path.Join(dirName, fileName), false)
	if err == nil {
		return WriteFile(path.Join(dirName, fileName), content, false)
	}
	return err
}

func MakeFileMd5(file multipart.File, ext ...byte) (md5Str string, err error) {
	if _, err = file.Seek(0, 0); err != nil {
		return
	}
	h := md5.New()
	if _, err = io.Copy(h, file); err != nil {
		return
	}
	md5Str = hex.EncodeToString(h.Sum(ext))
	if _, err = file.Seek(0, 0); err != nil {
		return
	}
	return
}
